package uit.cinemainfo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.net.Uri;
import android.os.Bundle;
import android.app.*;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.*;
import android.widget.*;

public class DetailFilmActivity extends Activity implements View.OnClickListener{
	public Film pro;
	public String newline = System.getProperty("line.separator");
	Intent intent;
	DBAdapter db;
	ImageView DetailPosterFilm;
	TextView DetailNameFilm;
	TextView DetailGenre;
	TextView DetailDuration;
	RatingBar DetailRatingFilm;
	TextView DetailVoteFilm;
	TextView DetailStart;
	TextView DetailDescription;
	TextView DetailCredit;
	Button btnVote;
	Button btnSche;
	Button btnTrailer;
	float newScore = 1;
	String[] listSche;
	String timePick;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_film);
		
		db = new DBAdapter(this);

		pro = new Film();
		intent = getIntent();

		if(intent != null) {
			try{
			int nofilm = intent.getIntExtra("nofilm", 1);
			db.open();
			Cursor p = db.getFilm(nofilm);
			pro = new Film(p.getString(0), p.getString(1), p.getInt(2), p.getString(3),p.getString(4),p.getString(5),p.getFloat(6),p.getString(7),p.getInt(8),p.getInt(9),p.getString(10),p.getInt(11));
			db.close();
			}catch (Exception ex){
				Log.w("Here", "ex la " + ex.getMessage());
				setResult(RESULT_OK);
				finish();
			}
		}
		else {
			setResult(RESULT_OK);
			finish();
		}
		
		DetailPosterFilm = (ImageView)findViewById(R.id.DetailPosterFilm);
		DetailNameFilm = (TextView)findViewById(R.id.DetailNameFilm);
		DetailGenre = (TextView)findViewById(R.id.DetailGenre);
		DetailDuration = (TextView)findViewById(R.id.DetailDur);
		DetailRatingFilm = (RatingBar)findViewById(R.id.DetailRatingFilm);
		DetailVoteFilm = (TextView)findViewById(R.id.DetailVoteFilm);
		DetailStart = (TextView)findViewById(R.id.DetailStart);
		DetailDescription = (TextView)findViewById(R.id.DetailDescription);
		DetailCredit = (TextView)findViewById(R.id.DetailCredit);
		btnVote = (Button)findViewById(R.id.btnVote);
		btnSche = (Button)findViewById(R.id.btnSche);
		btnTrailer = (Button)findViewById(R.id.btnTrailer);
		
		if(pro.image.endsWith("hobbit")){DetailPosterFilm.setImageResource(R.drawable.hobbit);}
		if(pro.image.endsWith("cold")){DetailPosterFilm.setImageResource(R.drawable.cold);}
		if(pro.image.endsWith("impo")){DetailPosterFilm.setImageResource(R.drawable.impo);}
		if(pro.image.endsWith("mis")){DetailPosterFilm.setImageResource(R.drawable.mis);}
		if(pro.image.endsWith("pi")){DetailPosterFilm.setImageResource(R.drawable.pi);}
		
		DetailNameFilm.setText(pro.namefilm);
		DetailGenre.setText(pro.kind);
		DetailDuration.setText(getResources().getString(R.string.duration) + ": " + pro.duration + " " + getResources().getString(R.string.mins));
		DetailRatingFilm.setRating((float)pro.score);
		DetailVoteFilm.setText(pro.numvote + " " + getResources().getString(R.string.vote));
		DetailStart.setText(getResources().getString(R.string.start) + ": " + pro.start);
		DetailDescription.setText(pro.description);
		DetailCredit.setText(getResources().getString(R.string.cast) + ": " + pro.credit);
		
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date showDate = new Date();
		try {
			showDate = dateformat.parse(pro.start + " 00:00:00");
		} catch (ParseException e) {
			Log.w("Here", e.getMessage());
			e.printStackTrace();
		}
		if(showDate.compareTo(new Date()) > 0)	{
			btnVote.setEnabled(false);
			btnSche.setEnabled(false);
		}
		btnVote.setOnClickListener(this);
		btnSche.setOnClickListener(this);
		btnTrailer.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_detail_film, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_showing:
	        	StartShowing();
	            return true;
	        case R.id.menu_coming:
	        	StartComing();
	            return true;
	        case R.id.menu_theater:
	        	StartTheater();
	        	return true;
	        case R.id.menu_news:
	        	StartNews();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public void StartComing(){
		Intent intent = new Intent(DetailFilmActivity.this, ComingActivity.class);
		startActivity(intent);
	}
	
	public void StartShowing(){
		Intent intent = new Intent(DetailFilmActivity.this, ShowingActivity.class);
		startActivity(intent);
	}
	
	public void StartTheater(){
		Intent intent = new Intent(DetailFilmActivity.this, TheaterActivity.class);
		startActivity(intent);
	}
	public void StartNews(){
		Intent intent = new Intent(DetailFilmActivity.this, ListNewsActivity.class);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
			case R.id.btnVote:
				GetVote();
				break;
			case R.id.btnSche:
				ViewSche();
				break;
			case R.id.btnTrailer:
				ViewTrailer();
				break;
		}
	}
	
	private void ViewSche() {
		db.open();
		
		Cursor p = db.getAllTheater();
		String[] listTheater = new String[p.getCount()];
        int i=0;
        if(p.moveToFirst()){
        	do{
        		listTheater[i] = p.getString(2) + newline + newline + getResources().getString(R.string.add) + ": " + p.getString(3) + newline;
        		i++;
        	}while (p.moveToNext());
        }
        db.close();
        try{
	        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setTitle(R.string.choosetitle);
	        builder.setItems(listTheater, new DialogInterface.OnClickListener(){
	
					@Override
					public void onClick(DialogInterface dialog, int which) {
						db.open();
						Cursor sche = db.getScheByFilmCine(pro.nofilm, which + 1);
						listSche = new String[sche.getCount()];
						int j=0;
				        if(sche.moveToFirst()){
				        	do{
				        		listSche[j] = sche.getString(3) + newline;
				        		j++;
				        	}while (sche.moveToNext());
				        }
				        AlertDialog.Builder schebuilder = new AlertDialog.Builder(DetailFilmActivity.this);
				        schebuilder.setTitle(R.string.choosesche);
				        schebuilder.setItems(listSche, new DialogInterface.OnClickListener(){

							@Override
							public void onClick(DialogInterface dialog,
									int which) {}				        	
				        });
				        schebuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener(){

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
				        });
				        
				        AlertDialog schedialog = schebuilder.create();
				        schedialog.show();
				        db.close();
					}});
	        AlertDialog dialog = builder.create();
	        dialog.show();
        }catch(Exception ex){Log.w("Here", ex.getMessage());}		
	}

	public void UpdateVote() {
		db.open();
		if(db.updateVoteFilm(pro.nofilm, newScore, pro.numvote + 1)){
			pro.numvote++;
			pro.score = newScore;
			DetailVoteFilm.setText(pro.numvote + " " + getResources().getString(R.string.vote));
			DetailRatingFilm.setRating((float)pro.score);
			btnVote.setEnabled(false);
		}
		db.close();
	}

	public void GetVote(){
		final Dialog rankDialog = new Dialog(this);
        rankDialog.setContentView(R.layout.voting_layout);
        rankDialog.setTitle(R.string.vote);
        rankDialog.setCancelable(true);
        Button CancelButton = (Button) rankDialog.findViewById(R.id.rank_dialog_button_Cancel);
        CancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rankDialog.dismiss();
            }
        });
        Button OKButton = (Button) rankDialog.findViewById(R.id.rank_dialog_button_OK);
        OKButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	RatingBar ratingBar = (RatingBar)rankDialog.findViewById(R.id.dialog_ratingbar);
            	newScore = (float)((pro.score * pro.numvote) + ratingBar.getRating()) / (float)(pro.numvote + 1);
            	UpdateVote();
                rankDialog.dismiss();
            }
        });
        rankDialog.show();                
    }
	
	public void ViewTrailer(){
		startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=" + pro.trailer)));
	}
}

